package com.banmao.algorithm.No201To300.No257;

import java.util.ArrayList;
import java.util.List;

public class Solution1 {

    public List<String> binaryTreePaths(TreeNode root) {

        ArrayList<TreeNode> list = new ArrayList<TreeNode>();
        ArrayList<String> result = new ArrayList<>();

        if(root == null) {
            return result;
        }

        list.add(root);

        recursive(list, result);

        return result;

    }

    public void recursive(List<TreeNode> list, List<String> result) {

        if(list.size() == 0) {
            return;
        }

        TreeNode treeNode = list.get(list.size() - 1);
        if(treeNode.left == null && treeNode.right == null) {
            // 是叶子节点 遍历list 输出到result
            StringBuilder sb = new StringBuilder();
            for (TreeNode node : list) {
                if(node == treeNode) {
                    sb.append(node.val);
                } else {
                    sb.append(node.val).append("->");
                }
            }
            result.add(sb.toString());
        } else {
            if(treeNode.left != null) {
                list.add(treeNode.left);
                recursive(list, result);
                list.remove(list.size() - 1);
            }

            if(treeNode.right != null) {
                list.add(treeNode.right);
                recursive(list, result);
                list.remove(list.size() - 1);
            }
        }
    }


}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
